<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Account_Controller extends CI_Controller {

	function __construct() {
		parent::__construct();
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$this->load->model('user', '', TRUE);
		$this->load->model('group_model', '', TRUE);
		if (!$this->session->userdata('logged_in')) {
			redirect('login');
		}

		$this->load->library('authentication');
		$this->load->helper('t');
		$this->loggedUser = $this->authentication->getLoggedUser();
		$this->authentication->redirectIfNotBe(array('RSM', 'KAM'));
	}

	function index($user_id, $resultstatus = '') {
		$viewData['title'] = "Thay đổi thông tin tài khoản";
		$logged_in = $this->session->userdata('logged_in');
		$user_id = $logged_in['id'];

		$viewData['user'] = $this->user->get_user($user_id);
		//$viewData['allgroups'] = $this->group_model->get_allgroups();
		$viewData['user_id'] = $user_id;
		if ($resultstatus != '') {
			$viewData['updateResult'] = $resultstatus;
		}
		$viewData['su'] = $logged_in['su'];

		$this->load->view(get_folder($this->loggedUser->title) . '/account_edit', $viewData);
	}

	// update user in database
	function update($user_id) {
		// form validations
		$logged_in = $this->session->userdata('logged_in');
		//if ($logged_in['su'] == "0") {
		$user_id = $logged_in['id'];
		//}

		$this->form_validation->set_rules('name', 'Họ tên', 'required');
		$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]');
		$this->form_validation->set_rules('user_password', 'Password', 'min_length[4]|password_check');
		$this->form_validation->set_message('password_check', 'Password chỉ cho phép số và chữ');
		$this->form_validation->set_rules('user_email', 'Email', 'required|valid_email');


		if ($this->input->post('user_password') != "") {
			$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[user_password]');
			$this->form_validation->set_message('required', 'Bắt buộc xác nhận password vì có thay đổi password');
		}


		$this->form_validation->set_message('matches', 'Hai password không giống nhau');
		if ($this->form_validation->run() == FALSE) {
			$this->index($this->loggedUser->id);
		} else {
			$infoToUpdate = array(
				'id' => $this->loggedUser->id,
				//'name' => $this->input->post('name'),
				//'password' => md5($this->input->post('user_password'))
			);
                        
                        if ($this->input->post('user_password') != "") {
				$infoToUpdate['password'] = md5($this->input->post('user_password'));
			}

			$updateResult = $this->user->update($infoToUpdate);
			$this->index($user_id, $updateResult);
		}
	}

}
?>